import asyncio
from pathlib import Path
import os
from conf import BASE_DIR
# from tk_uploader.main import tiktok_setup, TiktokVideo
from tk_uploader.main_chrome import tiktok_setup, TiktokVideo
from utils.files_times import generate_schedule_time_next_day, get_title_and_hashtags


def excute_tk_upload():
    filepath = Path(BASE_DIR) / "videos" / "主页作品" / "走路摇zly" / "视频作品"
    account_file = Path(BASE_DIR / "tk_uploader" / "account.json")
    # 获取视频目录
    folder_path = Path(filepath)
    # 获取文件夹中的所有文件
    files = list(folder_path.glob("*.mp4"))
    file_num = len(files)
    publish_datetimes = generate_schedule_time_next_day(file_num, 1, daily_times=[16])
    cookie_setup = asyncio.run(tiktok_setup(account_file, handle=True))
    for index, file in enumerate(files):
        title, tags = get_title_and_hashtags(str(file))
        thumbnail_path = file.with_suffix('.png')
        print(f"video_file_name：{file}")
        print(f"video_title：{title}")
        print(f"video_hashtag：{tags}")
        if thumbnail_path.exists():
            print(f"thumbnail_file_name：{thumbnail_path}")
            app = TiktokVideo(title, file, tags, publish_datetimes[index], account_file, thumbnail_path)
        else:
            app = TiktokVideo(title, file, tags, publish_datetimes[index], account_file)
        asyncio.run(app.main(), debug=False)


def delete_video_file():
    dir_path = Path(BASE_DIR) / "videos" / "主页作品" / "走路摇zly" / "视频作品"
    if not os.path.exists(dir_path):
        print('文件目录不存在')
        return

    for filename in os.listdir(dir_path):
        file_path = os.path.join(dir_path, filename)
        os.unlink(file_path)


if __name__ == '__main__':
    # filepath = Path(BASE_DIR) / "videos"
    # account_file = Path(BASE_DIR / "tk_uploader" / "account.json")
    # folder_path = Path(filepath)
    # # get video files from folder
    # files = list(folder_path.glob("*.mp4"))
    # file_num = len(files)
    # publish_datetimes = generate_schedule_time_next_day(file_num, 1, daily_times=[16])
    # cookie_setup = asyncio.run(tiktok_setup(account_file, handle=True))
    # for index, file in enumerate(files):
    #     title, tags = get_title_and_hashtags(str(file))
    #     thumbnail_path = file.with_suffix('.png')
    #     print(f"video_file_name：{file}")
    #     print(f"video_title：{title}")
    #     print(f"video_hashtag：{tags}")
    #     if thumbnail_path.exists():
    #         print(f"thumbnail_file_name：{thumbnail_path}")
    #         app = TiktokVideo(title, file, tags, publish_datetimes[index], account_file, thumbnail_path)
    #     else:
    #         app = TiktokVideo(title, file, tags, publish_datetimes[index], account_file)
    #     asyncio.run(app.main(), debug=False)
    print('开始执行tk上传')
    excute_tk_upload()
    print('tk视频上传成功，开始删除视频相关文件')
    delete_video_file()
